function r = logsumexpvec(v)
% Calculates the sum of a vector of probabilities that are loged.
%
% 2012 Maarten Inja & Chiel Kooijman.

if length(v) == 1
    r = v;
elseif length(v) == 2
    a1 = max(v);
    b1 = min(v);
    r = a1 + log(1 + exp(b1 - a1));
else
    v = sort(v, 'descend');
    a = v(1);
    b = v(2);
    t = a + log(1 + exp(b - a));
    r = logsumexpvec([t v(3:end)]);
end

